const { exec, spawn } = require('child_process');
const { promisify } = require('util');
const execPromise = promisify(exec); // 将 exec 转换为 Promise 形式
const koaSend = require('koa-send');
const path = require('path');
const fs = require('fs');

let apilist = require('./api/apilist')


function serverroute(router) {

  // 下载文件接口
  router.get('/download', async (ctx) => {
    const filePath = ctx.query.file;  // 获取查询参数中的 file
    // 拼接成完整的文件路径
    // const fullPath = path.join(__dirname, filePath);

    try {
      if (fs.existsSync(filePath)) {
        const fileStream = fs.createReadStream(filePath);
  
        // 设置响应头，告诉浏览器是下载文件
        ctx.set('Content-Disposition', 'attachment; filename=' + encodeURIComponent(path.basename(filePath)));
        ctx.set('Content-Type', 'application/octet-stream');
        // 将流直接发送到客户端
        ctx.body = fileStream;
      }
    } catch (err) {
      ctx.status = 404;
      ctx.body = 'File not found';
    }


  })


  // 打开本地文件选择器
router.get('/openfile', async (ctx) => {
  try {
    // 执行命令
    // 设置中文输出
    await execPromise('chcp 65001')

    const { stdout, stderr } = await execPromise(
      `powershell.exe -Command "& {Add-Type -AssemblyName System.Windows.Forms; $folderDialog = New-Object System.Windows.Forms.FolderBrowserDialog; $folderDialog.Description = '请选择文件夹'; $folderDialog.RootFolder = [System.Environment+SpecialFolder]::MyComputer; $result = $folderDialog.ShowDialog(); if ($result -eq [System.Windows.Forms.DialogResult]::OK) { Write-Output $folderDialog.SelectedPath } else { Write-Output '' } }"`
    );

    // 返回结果
    ctx.body = {
      code: 200,
      data: stdout.trim(),
    };
  } catch (error) {
    ctx.status = 500;
    ctx.body = { error: error.message };
  }
});

// 提交任务（把文件夹文件列表内容提交）
router.post('/submitdir', async (ctx) => {
  try {
    const body = ctx.request.body;
    let res = await apilist.submitDir(body)

    ctx.body = {
      code: 200,
      data: 'success'
      // data: JSON.stringify(res)
    }

  } catch (error) {
    ctx.status = 500;
    ctx.body = { error: error.message };
  }
});

// 获取监控文件夹列表
router.get('/getdirlist', async (ctx) => {
  try {
    let res = await apilist.getDirList()
    ctx.body = {
      code: 200,
      data: res
      // data: JSON.stringify(res)
    }

  } catch (error) {
    ctx.status = 500;
    ctx.body = { error: error.message };
  }
});

// 清空接口
router.get('/emptyimglist', async (ctx) => {
  try {
    let res = await apilist.emptyImgList()
    ctx.body = {
      code: 200,
      data: res
      // data: JSON.stringify(res)
    }

  } catch (error) {
    ctx.status = 500;
    ctx.body = { error: error.message };
  }
});

// 获取文件夹下文件详情列表
router.get('/dirimglist', async (ctx) => {
  try {

    let dirpath = decodeURIComponent(ctx.query.dirpath)
    // 替换为你的 exe 绝对路径
    let res = await apilist.getDirFileList(dirpath)
    ctx.body = {
      code: 200,
      data: res
      // data: JSON.stringify(res)
    }
  } catch (error) {
    ctx.status = 500;
    ctx.body = { error: error.message };
  }
});
}

exports.serverroute = serverroute